/*  
 * Copyright (C) 2011 Marta Spodymek
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *  
 */
package org.prometheuscode.web.feedback.dao;

import java.util.List;

import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.prometheuscode.web.feedback.domain.Feed;
import org.prometheuscode.web.feedback.domain.IFeed;
import org.springframework.transaction.annotation.Transactional;

/**
 * Access to feeds in data source.
 * 
 * @author marta
 * 
 */
public class FeedDao implements IFeedDao {

    private SessionFactory sessionFactory;

    public FeedDao() {

    }

    public SessionFactory getSessionFactory() {
	return this.sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
	this.sessionFactory = sessionFactory;
    }

    @Transactional(readOnly = true)
    @Override
    public List<IFeed> getAllUserFeeds(String userLogin) {

	Session sess = this.sessionFactory.getCurrentSession();

	List<IFeed> feeds = sess.createCriteria(Feed.class)
		.createCriteria("user")
		.add(Restrictions.eq("login", userLogin)).list();

	return feeds;
    }

    @Transactional(readOnly = true)
    @Override
    public IFeed getFeed(String feedId) {

	Session sess = this.sessionFactory.getCurrentSession();
	IFeed feed = (IFeed) sess.get(Feed.class, feedId);

	return feed;

    }

    @Transactional(readOnly = true)
    @Override
    public IFeed getFeedWithInputs(String feedId) {

	Session sess = this.sessionFactory.getCurrentSession();

	/*
	 * read form display data
	 */
	IFeed feed = (IFeed) sess.createCriteria(Feed.class)
		.add(Restrictions.eq("id", feedId))
		.setFetchMode("userFormInput", FetchMode.JOIN)
		.setFetchMode("user", FetchMode.JOIN).uniqueResult();

	return feed;
    }

    @Transactional
    @Override
    public void saveFeedInputs(IFeed updatedFeed) {

	Session sess = this.sessionFactory.getCurrentSession();
	sess.saveOrUpdate(updatedFeed);
    }

}
